package com.property.demo.repository;

import com.property.demo.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    Optional<User> findByUsername(String username);
    
    Boolean existsByUsername(String username);
    
    Boolean existsByEmail(String email);
    
    Page<User> findByUsernameContaining(String username, Pageable pageable);
    
    @Query("SELECT u FROM User u JOIN UserRole ur ON u.id = ur.userId JOIN Role r ON ur.roleId = r.id WHERE r.code = :roleCode")
    Page<User> findByRoleCode(@Param("roleCode") String roleCode, Pageable pageable);
    
    @Query("SELECT u FROM User u JOIN UserRole ur ON u.id = ur.userId JOIN Role r ON ur.roleId = r.id WHERE u.username LIKE %:username% AND r.code = :roleCode")
    Page<User> findByUsernameContainingAndRoleCode(@Param("username") String username, @Param("roleCode") String roleCode, Pageable pageable);
} 